﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;
using System.IO.IsolatedStorage;
using Microsoft.Xna.Framework.Media;
using System.Windows.Media.Imaging;
using System.IO;

namespace TM.QWeibo.Client.Tweet
{
    public partial class Image : PhoneApplicationPage
    {
        private string _imageUrl = "";

        public Image()
        {
            InitializeComponent();
            this.ApplicationBar.BackgroundColor = (Color)App.Current.Resources["ApplicationBarBackgroundColor"];
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (NavigationContext.QueryString.ContainsKey(AppSetting.TweetImageParameterKey))
            {
                var url = NavigationContext.QueryString[AppSetting.TweetImageParameterKey];
                if (!string.IsNullOrWhiteSpace(url))
                {
                    url = string.Format("{0}/2000", url);
                    _imageUrl = url;
                    var html = "<html><head><title>Image</title></head><body style='width:100%;height:100%;text-align:center;background:#000;'><img src='" + url + "' alt='picture' style='width:98%;'/></body></html>";
                    var size = App.Current.RootVisual.RenderSize;
                    webBrowser.Width = size.Width;
                    webBrowser.Height = size.Height;
                    webBrowser.Background = new SolidColorBrush(Colors.White);
                    webBrowser.LoadCompleted += WebBrowserLoadCompleted;
                    webBrowser.NavigateToString(html);
                }
            }
        }

        private void WebBrowserLoadCompleted(object sender, NavigationEventArgs e) {
            loadingBar.IsIndeterminate=false;
        }

        private void btnBack_Click(object sender, EventArgs e)
        {
            if (NavigationService.CanGoBack)
            {
                NavigationService.GoBack();
            }
        }
        /// <summary>
        /// 保存图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            loadingBar.IsIndeterminate = true;
            WebClient w = new WebClient();
            w.OpenReadAsync(new Uri(_imageUrl));
            w.OpenReadCompleted += new OpenReadCompletedEventHandler(w_OpenReadCompleted);
        }

        private void w_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            MemoryStream ms = new MemoryStream();
            try
            {
                loadingBar.IsIndeterminate = false;
                BitmapImage source = new BitmapImage();
                source.SetSource(e.Result);
                MediaLibrary library = new MediaLibrary();
                WriteableBitmap bitmap = new WriteableBitmap(source);
                Extensions.SaveJpeg(bitmap, ms, bitmap.PixelWidth, bitmap.PixelHeight, 0, 100);
                ms.Seek(0, SeekOrigin.Begin);
                ms.Seek(0, SeekOrigin.Current);
                library.SavePicture(Guid.NewGuid().ToString()+".jpg", ms);
                ms.Close();
                (new Helper.MessageBoxHelper()).Show("保存图片成功！", "温馨提示", this.LayoutRoot);
            }
            catch
            {
                (new Helper.MessageBoxHelper()).Show("保存图片失败了，请重试！", "对不起", this.LayoutRoot);
            }
            finally
            {
                ms.Close();
            }
        }
    }
}